package com.mxpio.erp.sales.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.mxpio.erp.common.ModuleUtils;
import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.common.quality.entity.SoInQualityOrder;
import com.mxpio.erp.common.quality.entity.SoInQualityOrderLine;
import com.mxpio.erp.common.sales.entity.*;
import com.mxpio.erp.common.vo.NoticeClassVo;
import com.mxpio.erp.sales.policy.impl.DefaultRejectWithCheckPolicy;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.policy.OrderContext;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.sales.service.SalesOrderLineService;
import com.mxpio.erp.common.sales.service.SalesOrderService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.sales.policy.impl.DefaultRejectPolicy;
import com.mxpio.erp.sales.policy.impl.DefaultShippingPolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "SalesOrderController", description = "销售订单接口")
@RestController
@RequestMapping("/erp/sales/so/")
public class SalesOrderController {

    @Autowired
    private SalesOrderService salesOrderService;
    @Autowired
    private SalesOrderLineService salesOrderLineService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderLineService orderLineService;
    @GetMapping("list")
    @Operation(summary = "销售订单列表", description = "获取销售订单列表（无分页）", method = "GET")
    public Result<List<SalesOrder>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<SalesOrder> salesOrders = salesOrderService.list(SalesOrder.class, criteria);
        return Result.OK(salesOrders);
    }

    @GetMapping("page")
    @Operation(summary = "销售订单列表", description = "获取销售订单列表（分页）", method = "GET")
    public Result<Page<SalesOrder>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<SalesOrder> salesOrders = salesOrderService.listPage(SalesOrder.class, page, criteria);
        return Result.OK(salesOrders);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据bizNo获取销售订单", description = "根据bizNo获取销售订单", method = "GET")
    public Result<SalesOrder> getById(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        SalesOrder salesOrder = salesOrderService.getById(SalesOrder.class, bizNo);
        return Result.OK(salesOrder);
    }

    @RequestMapping("save")
    @Operation(summary = "保存销售订单", description = "保存销售订单")
    public Result<SalesOrder> save(@RequestBody SalesOrder salesOrder) {
        salesOrderService.save(salesOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof SalesOrderLine){
        			SalesOrder salesOrder = context.getParent();
                    ((SalesOrderLine) o).setBizNo(salesOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(salesOrder);
    }

    @DeleteMapping("remove/{bizNos}")
    @Operation(summary = "根据bizNo删除销售订单", description = "删除销售订单", method = "DELETE")
    @Transactional(readOnly = false)
    public Result<SalesOrder> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for(String key : bizNo){
        	Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
        	salesOrderLineService.removeBatch(SalesOrderLine.class, c);
            salesOrderService.delete(SalesOrder.class, key);
        }
        return Result.OK();
    }

    @PutMapping("submit/{bizNo}")
    @Operation(summary = "提交销售订单", description = "提交销售订单", method = "PUT")
    public Result<? extends Order> submit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
    		return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITING);
    	}else {
    		return Result.error("非开立状态不可提交");
		}
    }

    @PutMapping("audit/{bizNo}")
    @Operation(summary = "审核销售订单", description = "审核销售订单", method = "PUT")
    public Result<? extends Order> audit(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
    		return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITED);
    	}else {
    		return Result.error("非审核中状态不可审核");
		}
    }

    @PutMapping("abandon/{bizNo}")
    @Operation(summary = "弃审销售订单", description = "弃审销售订单", method = "PUT")
    public Result<? extends Order> abandon(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
        if (!so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode()) && !so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            return Result.error("非审核中、已审核状态不可弃审");
        }
        if (!so.getOrderStatus().equals(OrderStatusEnums.OrderStatus.PLAN.getStatusCode())&&!so.getOrderStatus().equals(OrderStatusEnums.OrderStatus.ORDERED.getStatusCode())){
            return Result.error("执行状态非计划、下达时不可弃审");
        }
        return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.CREATE);
    }

    @PutMapping("export/{bizNos}")
    @Operation(summary = "导出销售订单", description = "导出销售订单", method = "PUT")
    public Result<SalesOrder> export(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        //TODO:导出逻辑
        return Result.OK();
    }

    @PutMapping("open/{bizNo}")
    @Operation(summary = "打开销售订单", description = "打开销售订单", method = "PUT")
    public Result<? extends Order> open(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	return orderService.updateCloseStatus(so, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @Operation(summary = "关闭销售订单", description = "关闭销售订单", method = "PUT")
    public Result<? extends Order> close(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	return orderService.updateCloseStatus(so, OrderStatusEnums.CloseStatus.CLOSED);
    }

    @RequestMapping("execute/ship/{bizNo}")
    @Operation(summary = "发货", description = "发货")
    public Result<Object> shipExec(@PathVariable(name = "bizNo", required = true) String bizNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        SalesOrder so = salesOrderService.getById(SalesOrder.class, bizNo);

        OrderContext context = orderService.execute(so, new DefaultShippingPolicy(orderExcuteVo.getLines(),orderLineService));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @RequestMapping("execute/reject/{bizNo}")
    @Operation(summary = "退货", description = "退货")
    public Result<Object> rejectExec(@PathVariable(name = "bizNo", required = true) String bizNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        SalesOrder so = salesOrderService.getById(SalesOrder.class, bizNo);
        OrderContext context = null;
        if (ModuleUtils.contains("Quality") && true){
            //退货生成入库验收单
            context = orderService.execute(so, new DefaultRejectWithCheckPolicy(orderExcuteVo.getLines(),orderLineService));
        }else{
            //常规逻辑，生成普通退货通知单
            context = orderService.execute(so, new DefaultRejectPolicy(orderExcuteVo.getLines(),orderLineService));
        }
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @PutMapping("finish/{bizNo}")
    @Operation(summary = "销售订单强制完成", description = "销售订单强制完成", method = "PUT")
    public Result<? extends Order> finish(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
        if(OrderStatusEnums.OrderStatus.PROCESSING.getStatusCode().equals(so.getOrderStatus())){
            //校验明细 是否存在未执行完毕的发货、退货记录
            Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, bizNo);
            List<SalesOrderLine> salesOrderLines = salesOrderLineService.list(SalesOrderLine.class, c);
            if (salesOrderLines.size()>0){
                //计算数量字段
                NoticeClassVo shippingNoticeClazz = new NoticeClassVo(ShippingNotice.class, ShippingNoticeLine.class);
                NoticeClassVo rejectBillNoticeClazz = new NoticeClassVo(RejectBill.class, RejectBillLine.class);
                NoticeClassVo inQualityOrderClazz = new NoticeClassVo(SoInQualityOrder.class, SoInQualityOrderLine.class);//增加入库验收单 数据统计
                List<NoticeClassVo> noticeClassVos = new ArrayList<NoticeClassVo>();
                noticeClassVos.add(shippingNoticeClazz);
                noticeClassVos.add(rejectBillNoticeClazz);
                noticeClassVos.add(inQualityOrderClazz);
                orderLineService.handleBizOrderLineQuantity(salesOrderLines, noticeClassVos, OrderEnums.AccessType.OUT.getCode());
                for (SalesOrderLine orderItem:salesOrderLines){
                    if ((orderItem.getPlanQuantity()!=null &&orderItem.getPlanQuantity().compareTo(BigDecimal.ZERO)!=0)
                            || (orderItem.getPlanRejectQuantity()!=null && orderItem.getPlanRejectQuantity().compareTo(BigDecimal.ZERO)!=0)){
                        return Result.error("订单行存在未执行完毕的发货、退货记录，无法执行完成订单操作。");
                    }
                }
            }
            return orderService.updateOrderStatus(so, OrderStatusEnums.OrderStatus.FINISHED);
        }else{
            return Result.error("非执行状态不可执行完成订单操作");
        }
    }

    @PutMapping("clear/{bizNo}")
    @Operation(summary = "结算销售订单", description = "结算销售订单", method = "PUT")
    public Result<? extends Order> clear(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        SalesOrder so = salesOrderService.getById(SalesOrder.class, bizNo);
        if(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode().equals(so.getOrderStatus())){
            return orderService.updateOrderStatus(so, OrderStatusEnums.OrderStatus.CLEARED);
        }else{
            return Result.error("非已完成状态不可执行”结算结清“操作");
        }
    }

}
